﻿using Newtonsoft.Json;
using PLM.ConfigurationCenter.Handler;
using PLM.ConfigurationCenter.Model;
using PLM.ConfigurationCenter.Service;
using PLM.ConfigurationCenter.Core.Expansion;
using Sunny.UI;
using System;
using System.Windows.Forms;
using PLM.ConfigurationCenter.Service.Handler;
using PLM.ConfigurationCenter.SqlSugar;

namespace PLM.ConfigurationCenter.CustomForm {
    public partial class MainDbForm : UIForm {
        /// <summary>
        /// 
        /// </summary>
        private readonly CommonServerHelper _commonHelper = new CommonServerHelper();

        /// <summary>
        /// 
        /// </summary>
        public string DbId;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        public MainDbForm(string id) {
            InitializeComponent();
            DbId = id;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainDbForm_Load(object sender, EventArgs e) {
            var dbmodel = DbManager.DbContext.Queryable<DatabaseInfoModel>().First(p => p.Id == DbId);
            if (DbId == "BaseDb") {
                this.rbtn_pagsql.Enabled = false;
                this.rbtn_sql.Enabled = true;
                this.rbtn_oracle.Enabled = true;
            } else {
                this.rbtn_pagsql.Enabled = true;
                this.rbtn_sql.Enabled = false;
                this.rbtn_oracle.Enabled = false;
            }
            if (dbmodel == null) {
                int db = DbId == "BaseDb" ? 1 : 3;
                dbmodel = new DatabaseInfoModel { Id = DbId, DBType = db };
            }
            InitializeData(dbmodel);

            this.tb_dbip.TextChanged += textChange_Click;
            this.tb_dbname.TextChanged += textChange_Click;
            this.tb_dbport.TextChanged += textChange_Click;
            this.tb_dbserver.TextChanged += textChange_Click;
            this.tb_dbuser.TextChanged += textChange_Click;
            this.tb_userpw.TextChanged += textChange_Click;

        }
        /// <summary>
        /// 
        /// </summary>
        private void InitializeData(DatabaseInfoModel dbmodel) {
            this.tb_dbid.Text = dbmodel.Id;
            if (dbmodel.DBType == 1) {
                dbmodel.Port = 1433;
                this.rbtn_sql.Checked = true;
                this.tb_dbserver.ReadOnly = true;
            } else if (dbmodel.DBType == 2) {
                this.rbtn_oracle.Checked = true;
                dbmodel.Port = 1521;
                this.tb_dbserver.ReadOnly = false;
            } else {
                this.rbtn_pagsql.Checked = true;
                dbmodel.Port = 5432;
                this.tb_dbserver.ReadOnly = true;
            }
            dbmodel.IPAddress = ServerHandler.GetLocalIP();
            dbmodel.ServerName = dbmodel.DBType == 2 ? "orcl" : "";

            this.tb_dbip.Text = dbmodel.IPAddress;
            this.tb_dbname.Text = dbmodel.DbName;
            this.tb_dbport.Text = dbmodel.Port.ToString();
            this.tb_dbserver.Text = dbmodel.ServerName;
            this.tb_dbstr.Text = CommonServerHelper.GetDBConn(dbmodel);
            this.tb_dbuser.Text = dbmodel.UserName;
            this.tb_userpw.Text = dbmodel.Password;
        }
        /// <summary>
        /// 
        /// </summary>
        private void rbtn_oracle_Click(object sender, EventArgs e) {
            var dbmodel = DbManager.DbContext.Queryable<DatabaseInfoModel>().First(p => p.Id == DbId && p.DBType == 2);
            dbmodel ??= new DatabaseInfoModel { DBType = 2, Id = DbId };
            InitializeData(dbmodel);
        }
        /// <summary>
        /// 
        /// </summary>
        private void rbtn_sql_Click(object sender, EventArgs e) {
            var dbmodel = DbManager.DbContext.Queryable<DatabaseInfoModel>().First(p => p.Id == DbId && p.DBType == 1);
            dbmodel ??= new DatabaseInfoModel { DBType = 1, Id = DbId };
            InitializeData(dbmodel);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rbtn_pagsql_Click(object sender, EventArgs e) {
            var dbmodel = DbManager.DbContext.Queryable<DatabaseInfoModel>().First(p => p.Id == DbId && p.DBType == 3);
            dbmodel ??= new DatabaseInfoModel { DBType = 3, Id = DbId };
            InitializeData(dbmodel);
        }
        /// <summary>
        /// 
        /// </summary>
        private void tb_dbstr_DoubleClick(object sender, EventArgs e) {
            Clipboard.SetText(tb_dbstr.Text);
            MessageBox.Show("复制成功！");
        }
        /// <summary>
        /// 
        /// </summary>
        public void textChange_Click(object sender, EventArgs e) {
            this.tb_dbstr.Text = "";
            string str;
            if (this.rbtn_sql.Checked) {
                str = $"Data Source={this.tb_dbip.Text};Initial Catalog={this.tb_dbname.Text};User ID={this.tb_dbuser.Text};Password={this.tb_userpw.Text};";
            } else if (this.rbtn_oracle.Checked) {
                str = $"Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST={this.tb_dbip.Text})(PORT={this.tb_dbport.Text}))(CONNECT_DATA=(SERVER = DEDICATED)(SERVICE_NAME={this.tb_dbserver.Text})));User Id={this.tb_dbuser.Text};Password={this.tb_userpw.Text};";
            } else {
                str = $"PORT={this.tb_dbport.Text};DATABASE={this.tb_dbname.Text};HOST={this.tb_dbip.Text};PASSWORD={this.tb_userpw.Text};USER ID={this.tb_dbuser.Text};";
            }
            this.tb_dbstr.Text = str;
        }
        
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_save_Click(object sender, EventArgs e) {
            var error = CheckInputData();
            if (!error.IsEmpty()) {
                MessageBox.Show(error);
                return;
            }
            var model = new DatabaseInfoModel {
                IPAddress = this.tb_dbip.Text,
                DbName = this.tb_dbname.Text,
                Port = this.tb_dbport.Text.ToIntOrNull(),
                ServerName = this.tb_dbserver.Text,
                UserName = this.tb_dbuser.Text,
                Password = this.tb_userpw.Text,
                Id = this.tb_dbid.Text
            };
            if (this.rbtn_sql.Checked == true) {
                model.DBType = 1;
            } else if (this.rbtn_oracle.Checked == true) {
                model.DBType = 2;
            } else {
                model.DBType = 3;
            }
            DbManager.DbContext.Deleteable<DatabaseInfoModel>(p => p.Id == DbId).ExecuteCommand();
            DbManager.DbContext.Insertable(model).ExecuteCommand();
            MessageBox.Show("保存成功！");
        }
        /// <summary>
        /// 重置
        /// </summary>
        private void btn_reset_Click(object sender, EventArgs e) {
            DbManager.DbContext.Deleteable<DatabaseInfoModel>(p => p.Id == DbId).ExecuteCommand();
            MessageBox.Show("重置成功！");
            int db = DbId == "BaseDb" ? 1 : 3;
            var dbmodel = new DatabaseInfoModel { Id = DbId, DBType = db };
            InitializeData(dbmodel);
        }
        /// <summary>
        /// 测试连接
        /// </summary>
        private void btn_test_Click(object sender, EventArgs e) {
            var error = CheckInputData();
            if (!error.IsEmpty()) {
                MessageBox.Show(error);
                return;
            }
            int dbtype;
            if (this.rbtn_sql.Checked) {
                dbtype = 1;
            } else if (this.rbtn_oracle.Checked) {
                dbtype = 2;
            } else {
                dbtype = 3;
            }
            var res = _commonHelper.CheckHealth(dbtype, this.tb_dbstr.Text);
            if (res.IsEmpty()) {
                MessageBox.Show("连接成功！");
            } else {
                MessageBox.Show("连接失败！" + res);
            }
        }
        /// <summary>
        /// 检查输入数据
        /// </summary>
        private string CheckInputData() {
            var user = this.tb_dbuser.Text.Trim();
            if (user.IsEmpty()) {
                return "没有输入数据库账号！";
            }
            var userpw = this.tb_userpw.Text.Trim();
            if (userpw.IsEmpty()) {
                return "没有输入数据库密码！";
            }
            var dbname = this.tb_dbname.Text.Trim();
            if (dbname.IsEmpty()) {
                return "没有输入数据库名称！";
            }
            if (this.rbtn_oracle.Checked) {
                var dbserver = this.tb_dbserver.Text.Trim();
                if (dbserver.IsEmpty()) {
                    return "没有输入服务名称！";
                }
            }
            return "";
        }

    }
}
